<template>
  <div class="layout-padding row justify-center">
    <div style="width: 600px; max-width: 100vw;">
      <q-stepper ref="downpicProcess" color="blue-grey"  vertical>
        <q-step default name="setting" title="设置压缩质量">
          压缩质量：
          <span style="color:red;font-size:1.4em">{{qualityPress}}</span>
          <p class="caption">
              <span>tip:值越大压缩程度越小⚠️建议在web端使用 </span>
              <q-slider v-model="qualityPress" :min="1" :max="10" label  />
          </p>
          <q-stepper-navigation>
            <q-btn color="dark" @click="$refs.downpicProcess.next()">next</q-btn>
          </q-stepper-navigation>
        </q-step>

        <q-step name="choice" title="选择压缩图片">
            图片数量：
          <span style="color:red;font-size:1.4em">{{picCount}}</span>
          <p class="caption">⚠️最多一次处理10张图片哦,而且图片大小要保持在10M以内</p>
          <q-btn color="faded" class="full-width"  @click="choiceFile" icon="photo library">选择图片</q-btn>
                <!-- capture="camera"  -->
                <input id="upload" ref="selectImage" type="file" accept="image/*" @change="selectImageAction($refs.selectImage.files)"
                        multiple style="display: none;width:0;height:0"/>
          <q-stepper-navigation>
            <q-btn color="dark" @click="$refs.downpicProcess.next()">next</q-btn>
            <q-btn color="orange" flat @click="$refs.downpicProcess.previous()">后退</q-btn>
          </q-stepper-navigation>
        </q-step>

        <q-step name="download" title="下载压缩结果">
          <p>
            <q-btn color="faded" class="full-width"  @click="downpic">下载文件</q-btn>
          </p>
          <q-stepper-navigation>
            <q-btn color="dark" @click="resetStep">重置</q-btn>
            <q-btn color="orange" flat @click="$refs.downpicProcess.previous()">后退</q-btn>
          </q-stepper-navigation>
        </q-step>

        <q-inner-loading :visible="showProgress" />
      </q-stepper>


    </div>
  </div>
</template>

<script>
import {
  Alert,
  Ripple,
  QBtn,
  Dialog,
  QSlider,
  QStepper,
  QStep,
  QStepperNavigation,
  QInnerLoading
} from "quasar";
import commonApiHttp from "../../../https/commonApi";
import customerApi from "../../../https/customerApi";
import Storage from "../../../utils/storage";
import PicUtils from "../../../utils/PicUtils";
import ImagePlus from '../../../utils/ImagePlus';
export default {
  components: {
    QBtn,
    Alert,
    Dialog,
    QSlider,
    QStepper,
    QStep,
    QStepperNavigation,
    QInnerLoading
  },
  directives: {
    Ripple
  },
  data() {
    return {
      qualityPress: 5,
      imagesSrc: [], //原始图片
      picCount: 0,
      showProgress: false,
      isWin:true
    };
  },
  props: {
    enablePicChoice: { type: Boolean, default: true },
    isAddIcon: { type: Boolean, default: true }
  },
  
  mounted() {
    // this.$refs.inputModal.open();
  },
  methods: {
    clearDatas(){
      this.imagesSrc = [];
      this.picCount = 0;
      this.showProgress = false;
      let _temp = document.getElementById("upload");
      if(_temp != null) {
        _temp.value = '';
      }
    },
    alertMsg(msg) {
      if (msg) {
        const _errAlert = Alert.create({
          color: "warning",
          icon: "info",
          html: msg,
          position: "bottom"
        });
        setTimeout(() => {
          _errAlert.dismiss();
        }, 3000);
      }
    },
    checkFile(file) {
      //校验文件
      //类型
      if (
        !file ||
        !file.name ||
        !/.*(.jpg|.png|.gif|.jpeg|bmp)$/.test(file.name)
      ) {
        this.alertMsg("抱歉，不支持的文件类型");
        return false;
      }
      //大小
      if (file.size > 10485760) {
        this.alertMsg("抱歉，文件大小超出了10M的限制");
        return false;
      }
      return true;
    },
    choiceFile(){
      
      /**20180222 TODO 文件选择 */

      if(this.isWin) {
        this.$refs.selectImage.click();
      }else {
        this.alertMsg('此功能建议在web端使用')
        return false;

        // ImagePicker.getPictures(result=> {
        //   ImagePlus.showImage(result);
        //   console.log('选择的文件：',result);
        //   this.selectImageAction(result,false);
        // }, err=> {
        //   alert(err);
        // }, { maximumImagesCount: 9, width: 1920, height: 1440, quality: 100 });
      }
    },
    selectImageAction(res,ischeck) {
      //文件选择处理
      const newCount = res.length;
      if (this.picCount + newCount > 10) {
        this.alertMsg("抱歉，最多一次压缩10张图片");
        return false;
      }
      const reader = new FileReader();
      if (typeof FileReader === "undefined") {
        this.alertMsg("抱歉，您的设备不支持图片压缩处理");
        //不支持类型的处理
        return false;
      }
      //校验类型，大小
      if(ischeck) {
        for (let i = 0; i < newCount; i++) {
          if (!this.checkFile(res[i], false)) {
            return false;
          }
        }
      }
      //多选
      this.showProgress = true;
      this.picCount = this.picCount + newCount;
      let numbers = newCount - 1;
      const _wait = setInterval(() => {
        if (numbers < 0) {
          this.showProgress = false;
          clearInterval(_wait);
        } else {
          const fileObj = res[numbers];
          PicUtils.photoCompress(
            //压缩
            fileObj,
            {
              quality: this.qualityPress / 10
            },
            base64Codes => {
              const bl = PicUtils.convertBase64UrlToBlob(base64Codes);
              console.log("压缩前：", fileObj.size, "压缩后：", bl.size);
              this.imagesSrc.push(bl);
              numbers--;
            }
          );
        }
      }, 1000);
      console.log('上传：', document.getElementById("upload").value );
    },
    downpic() {
      console.log("当前文件：", this.imagesSrc);
      var aLink = document.createElement("a");
      const nowdate = Date.parse(new Date());
      const _obj = this.imagesSrc;
      for (const i in _obj) {
        if (_obj.hasOwnProperty(i)) {
          const data = _obj[i];
          aLink.download = nowdate+i+".jpg";
          console.log("文件：", data);
          aLink.href = window.URL.createObjectURL(data);
          aLink.click();
        }
      }
      this.clearDatas();
    },
    resetStep() {
      this.$refs.downpicProcess.goToStep('setting');
      this.clearDatas();
    }
  }
};
</script>
